<template>
    <div class="pe-textarea" :style="{ resize: resize, '--pe-textarea-border-color': borderColor }">
        <textarea class="pe-textarea-inner" v-model="value" :name="name" :id="id" :cols="cols" :rows="rows" :maxlength="maxlength" @blur="blur"
            @focus="focus" @change="change" @input="input"></textarea>
        <span v-if="showWordCount" class="pe-textarea-count">{{ value.length }}{{ maxlength !== undefined ?
            `/${maxlength}` : '' }}</span>
        <div v-if="disabled" class="pe-disabled"></div>
    </div>
</template>

<script setup lang="ts">
import { ref } from "vue"

const value = defineModel({type: String, default: ""})

/**
 * @param name 原生 textarea name 属性
 * @param id 原生 textarea id 属性
 * @param cols 原生 textarea cols 属性，文本域列数量
 * @param rows 原生 textarea rows 属性，文本域行数量
 * @param disabled 是否禁用
 * @param resize 文本域拖拽方向
 * @param maxlength 最大输入字符数量
 * @param show-word-count 是否显示字符数量
 */
interface Props {
    name?: string,
    id?: string,
    cols?: number,
    rows?: number,
    disabled?: boolean,
    resize?: 'none' | 'both' | 'horizontal' | 'vertical' | 'block' | 'inline',
    maxlength?: number,
    showWordCount?: boolean
}

withDefaults(defineProps<Props>(), {
    cols: 30,
    rows: 3,
    disabled: false,
    resize: "none",
    showWordCount: false
})

const emits = defineEmits(["blur", "focus", "change", "input"])

const borderColor = ref<string>("")
// 失去焦点事件
const blur = () => {
    borderColor.value = "var(--pe-color-border)"
    emits("blur")
}

// 获取焦点事件
const focus = () => {
    borderColor.value = "var(--pe-color-primary)"
    emits("focus")
}

// 仅当 modelValue 改变时，当输入框失去焦点或用户按Enter时触发
const change = () => {
    emits("change", value.value)
}

// 在 Input 值改变时触发
const input = () => {
    emits("input", value.value)
}
</script>

<script lang="ts">
export default {
    name: "pe-textarea"
}
</script>
